import React, { Suspense } from "react";
import PageLoading from "@/components/PageLoading";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import GridContent from "@/components/PageHeaderWrapper/GridContent";
import { Tabs, Icon, Tooltip, Form, message, Button} from "antd";
import TabPaneModal from "@/pages/Dialog/tabCategory/tabPaneModal";
import DialogList from "@/pages/Dialog/List/index";
import EditPaneModal from "./editPaneModal";
import { connect } from "dva";
import UserSession from "@/UserSession";
import styles from "./tabCategory.less";
import { knowledgeListDialog, knowledgeDialogCategoryInfo } from '@/services/dialog';
import { postDialogCategoryAdd, postDialogCategoryEdit, getDialogCategoryDel } from "@/services/knowledgeCategory";
import ReferenceTemplate from './referenceTemplate';

class TabCategory extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			tabPaneList: [],
			dialogList: [],
			dialogTotal: 0,
			dialogLoading: false,
			dialogCategoryId: "",
		};
	}

	componentDidMount() {
		this.getTabList();
	}

	/**
	 * 获取分类
	 */
	getTabList = async () => {
		const { dispatch, match: { params: { id } } } = this.props;
		console.log(this.props);
		if(UserSession.isSystemKnowledge()) {
			let res = await knowledgeDialogCategoryInfo({ categoryId: id });
			// console.log(res);
			this.setState({ tabPaneList: res, }, () => {
				this.fetchDialogList(15, 1);
			});
		} else {
			dispatch({
				type: "dialogLists/getDialogCategory",
				payload: {
					categoryId: id,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					// console.log(res);
					this.setState({ tabPaneList: res, }, () => {
						this.fetchDialogList(15, 1);
					});
				},
			});
		}
	};

	/**
	 * 分类管理
	 * @returns {*}
	 */
	tabPaneManage = () => {
		const { tabPaneList } = this.state;
		this.TabPaneModal.openModal(tabPaneList);
	};
	addManage = () => {
		this.EditPaneModalRef.openModal()
	}

	editManage = () => {
		const { tabPaneList, dialogCategoryId } = this.state;
		let row = tabPaneList.filter(item => item.id == dialogCategoryId);
		this.EditPaneModalRef.openModal(row[0]);
	}

	setCategory = async (name, categoryId) => {
		const { dispatch, match: { params: { id }, }, } = this.props;
		let obj = { name, rootCategoryId: id };
		let res = { code: -1, data: false, msg: '操作成功' };
		if (categoryId) {
			obj.id = categoryId;
			res = await postDialogCategoryEdit(obj)
		} else {
			res = await postDialogCategoryAdd(obj);
		};
		if (res.code === 0) {
			message.success('操作成功')
			this.EditPaneModalRef.closeModal()
		}
	}

	delManage = async () => {
		const { tabPaneList, dialogCategoryId } = this.state;
		let row = tabPaneList.filter(item => item.id == dialogCategoryId);
		let res = await getDialogCategoryDel({ id: row[0]?.id })
		if (res.code === 0) {
			message.success("操作成功");
			this.setState({ dialogCategoryId: "" }, () => this.getTabList())
		}
	}


	/**
	 * 切换分类
	 * @returns {*}
	 */
	changeTab = (key) => {
		this.setState({ dialogCategoryId: key, }, () => {
			this.fetchDialogList(15, 1);
		});
	};

	/**
	 * 根据分类获取相应图谱
	 * @returns {*}
	 */
	fetchDialogList(limit, page) {
		const { dialogCategoryId } = this.state;
		const { dispatch, match: { params: { id } } } = this.props;
		this.setState({ dialogLoading: true }, async () => {
			if (UserSession.isSystemKnowledge()) {
				let res = await knowledgeListDialog({
					current: page,
					size: limit,
					rootCategoryId: id,
					categoryId: dialogCategoryId ? dialogCategoryId : undefined,
				});
				this.setState({
					dialogTotal: res.total,
					dialogList: res.records,
					dialogLoading: false,
				});
			} else {
				dispatch({
					type: "dialogList/fetchList",
					payload: {
						limit,
						page,
						rootCategoryId: id,
						categoryId: dialogCategoryId ? dialogCategoryId : undefined,
						urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
					},
					callback: (res) => {
						this.setState({
							dialogTotal: res.total,
							dialogList: res.records,
							dialogLoading: false,
						});
					},
				});
			}
		});
	}

	/**
	 * 子组件传值
	 * @returns {*}
	 */
	fetchDialogListByPage = (limit, page) => {
		this.fetchDialogList(limit, page);
	};

	reference = () => {
		const { dialogCategoryId } = this.state;
		if (this.referenceTemplateRef) {
			this.referenceTemplateRef.init({ type: "classify", id: dialogCategoryId })
		}
	}

	render() {
		const { tabPaneList, dialogList, dialogTotal, dialogLoading, dialogCategoryId } = this.state;
		const { match: { params: { id } }, location } = this.props;
		const operations = UserSession.isSystemKnowledge() && dialogCategoryId !== '' ? (
			<Button icon="block" style={{ margin: '12px 0' }} onClick={this.reference}>引用</Button>
		) : UserSession.whetherCanDelete() ? null : (
			// <Button icon="unordered-list" style={{ margin: '12px 0' }} onClick={this.tabPaneManage}>分类管理</Button>
			<span style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
				{/* <Button icon='unordered-list' style={{ margin: '12px 0' }} onClick={this.tabPaneManage}>分类管理</Button> */}
				<Tooltip placement="bottom" title="新增分类">
					<Button icon='plus' style={{ margin: '12px 0' }} onClick={this.addManage}></Button>
				</Tooltip>
				{dialogCategoryId !== '' ? (
					<>
						<Tooltip placement="bottom" title="编辑分类名称">
							<Button icon='form' style={{ margin: '12px 0' }} onClick={this.editManage}></Button>
						</Tooltip>
						<Tooltip placement="bottom" title="删除分类">
							<Button icon='delete' style={{ margin: '12px 0' }} onClick={this.delManage}></Button>
						</Tooltip>
					</>
				) : null}
			</span>
		);

		return (
			<GridContent>
				<Suspense fallback={<PageLoading />}>
					<div style={{ padding: "0 10px 15px" }} className={styles.tabCategoryCard}>
						<Tabs tabBarExtraContent={operations} defaultActiveKey={""} onChange={this.changeTab}>
							<Tabs.TabPane key={""} tab={"全部"}>
								<DialogList
									dialogCategoryId={""}
									tabPaneList={tabPaneList}
									list={dialogList}
									total={dialogTotal}
									dialogLoading={dialogLoading}
									fetchDialogListByPage={this.fetchDialogListByPage}
									pathId={id}
									location={location}
								/>
							</Tabs.TabPane>

							{tabPaneList.map((item) => {
								return (
									<Tabs.TabPane key={item.id} tab={item.name}>
										<DialogList
											dialogCategoryId={item.id}
											tabPaneList={tabPaneList}
											list={dialogList}
											total={dialogTotal}
											dialogLoading={dialogLoading}
											fetchDialogListByPage={this.fetchDialogListByPage}
											pathId={id}
											location={location}
										/>
									</Tabs.TabPane>
								);
							})}
						</Tabs>
					</div>
					<ReferenceTemplate onRef={ref => this.referenceTemplateRef = ref} />
					<EditPaneModal onRef={ref => this.EditPaneModalRef = ref} setCategory={this.setCategory} getTabList={this.getTabList} />
					<TabPaneModal onRef={(ref) => (this.TabPaneModal = ref)} tabPaneList={tabPaneList} getTabList={this.getTabList} id={id} />
				</Suspense>
			</GridContent>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(TabCategory);
